'use strict';
let dayjs = require('dayjs')
//import dayjs from 'dayjs' // ES 2015
dayjs().format()

const Service = require('egg').Service;
const {
  md5
} = require('utility');
const jwt = require('jsonwebtoken');

class UserService extends Service {
  async login() {
    const {
      ctx,
      app
    } = this;
    // 解构出用户民和密码
    const {
      name,
      password
    } = ctx.request.body;
    // 根据用户名和密码在数据库中查找对应的用户
    const userInfo = await app.mysql.get('user', {
      name,
      password: md5(JSON.stringify(password))
    });
    if (userInfo) {
      const token = jwt.sign({
        ...userInfo
      }, app.keys[0]);
      return {
        data: userInfo,
        token
      }
    } else {
      return "账户或密码错误"
    }

  }
  async register() {
    const {
      ctx,
      app
    } = this;
    const {
      name,
      password
    } = ctx.request.body;
    // 查找当前用户名是否已经被注册
    const userInfo = await app.mysql.get('user', {
      name,
    });
    if (userInfo) {
      return '当前用户名已经被注册'
    } else {
      // 插入数据
      const res = await app.mysql.insert('user', {
        name,
        password: md5(JSON.stringify(password)),
        role: "visitor",
        create_at: dayjs(Date.now()).format('YYYY-MM-DD hh:mm:ss'),
        update_at: dayjs(Date.now()).format('YYYY-MM-DD hh:mm:ss')
      });

      return res
    }
  }
  async getList() {
    const {
      ctx,
      app
    } = this;
    const {
      pageSize,
      pageIndex,
      name,
      email,
      status,
      role
    } = ctx.query;
    let sql = `select * from user where 1=1 `;
    let countSql = `select count(id) as total from user where 1=1 `
    if (name) {
      sql += `and name like "%${name}%" `
      countSql += `and name like "%${name}%" `
    }
    if (status) {
      sql += `and status="${status}" `
      countSql += `and status="${status}" `
    }
    if (role) {
      sql += `and role="${role}" `
      countSql += `and role="${role}" `
    }
    if (pageSize && pageIndex) {
      sql += `limit ${(pageIndex-1)*pageSize},${pageSize} `
    }
    const res = await app.mysql.query(sql);
    const [{
      total
    }] = await app.mysql.query(countSql);
    return {
      data: res,
      total,
    }
  }
  // 编辑用户
  async editUser() {
    const {
      ctx,
      app
    } = this;
    const {
      id,
      role,
      status
    } = ctx.request.body;
    console.log(role);
    console.log(status);
    let res = '编辑失败'
    if (role) {
      res = await app.mysql.update('user', {
        id,
        role: role,
      });
    }
    if (status) {
      res = await app.mysql.update('user', {
        id,
        status: status
      });
    }
    console.log(res);
    return res
  }
}

module.exports = UserService;